<?php 
require_once '../3rd_party/phpword/PHPWord.php';
$PHPWord = new PHPWord();
$tmpl_n = $tmpl . '_n';
$templates = $orm->get('pb_colg_template', NULL, NULL, NULL, NULL, NULL)->d;
if (count($templates) > 0 && file_exists($templates[0]->$tmpl)) {
  $doc = $PHPWord->loadTemplate($templates[0]->$tmpl);
  
  $opts = new stdClass();
  $opts->cd = 't.id = :v1';
  $opts->cdv = array(':v1' => $tmpl_id);
  $opts->sel = 't.*, t1.first_name AS __first_name, t1.last_name AS __last_name, t1.id_number AS __id_number, t1.date_of_birth AS __date_of_birth, t1.gender AS __gender';
  $opts->jt = 'LEFT JOIN pb_colg_student AS t1 ON t1.id = t.student_id';
  $data = $orm->get('pb_colg_invoice', NULL, NULL, NULL, NULL, $opts)->d;

  $data[0]->__fee_paid = $data[0]->amount + ($data[0]->balance__);
  $data[0]->__date = date('d M Y', time());
  $data[0]->balance__ = -($data[0]->balance__);
  ____setup($doc, $data[0]);
  
  $tmp = '../tmp/' . Utils::unique() . '.docx';
  $doc->save($tmp);
  
  $name = pathinfo($templates[0]->$tmpl_n, PATHINFO_FILENAME);
  $ext = pathinfo($templates[0]->$tmpl_n, PATHINFO_EXTENSION);
  header('Content-Disposition: attachment; filename="' . $name . '_' . $data[0]->particular . '_' . $data[0]->amount . '#' . $data[0]->__id_number . '.' . $ext . '"');
  readfile($tmp); // or echo file_get_contents($temp_file);
  unlink($tmp);  // remove temp file
}
?>